package com.opencee.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.opencee.common.security.SecurityConstants;
import com.opencee.common.security.SecurityProperties;
import com.opencee.common.security.SecurityUser;
import org.springframework.security.access.AccessDeniedException;

import java.util.Date;

public class JwtUtil {

    /**
     * 生成Jwt
     *
     * @param user 登录成功的user对象
     * @return
     */
    public static String createJWT(SecurityUser user, SecurityProperties properties) {
        String payload = JSON.toJSONString(user);
        // 随机生成密钥
        byte[] key = properties.getJwtClaimsAesKey().getBytes();
        // 构建
        AES aes = SecureUtil.aes(key);
        // 加密为16进制表示
        String encryptHex = aes.encryptHex(payload);
        // 放入私密信息
        final String token = JWT.create()
                .setExpiresAt(new Date(System.currentTimeMillis() + properties.getJwtExpires()))
                .setKey(properties.getJwtSigningKey().getBytes())
                .setPayload(SecurityConstants.PRIVATE_CLAIMS, encryptHex)
                .sign();
        return token;
    }


    /**
     * Token的解密
     *
     * @param token 加密后的token
     * @return
     */
    public static SecurityUser parseJWT(String token, SecurityProperties properties) {
        JWT jwt = null;
        SecurityUser securityUser = null;
        try {
            jwt = JWTUtil.parseToken(token);
        } catch (Exception e) {
            throw new AccessDeniedException("无效的token！");
        }

        if (!jwt.setKey(properties.getJwtSigningKey().getBytes()).verify()) {
            throw new AccessDeniedException("无效的token！");
        }

        if (!jwt.validate(0)) {
            throw new AccessDeniedException("无效的token,已过期！");
        }
        try {
            String privateClaims = jwt.getPayload().getClaim(SecurityConstants.PRIVATE_CLAIMS).toString();
            AES aes = SecureUtil.aes(properties.getJwtClaimsAesKey().getBytes());
            // 解密
            String decryptStr = aes.decryptStr(privateClaims).toString();
            securityUser = JSON.parseObject(decryptStr, SecurityUser.class);
        } catch (Exception e) {
            throw new AccessDeniedException("无效的token！");
        }
        return securityUser;
    }


    public static void main(String[] args) {
        SecurityProperties properties = new SecurityProperties();
        properties.setJwtExpires(1000);
        SecurityUser user = new SecurityUser();
        user.setUserId(2222L);
        user.setUsername("dasdas");
        String token = createJWT(user,properties);
        System.out.println(token);
        SecurityUser a = parseJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg3NTE4OTQsInByaXZhdGVDbGFpbXMiOiJiOTk3MzdmOTA0NDlhYTkxZWFhN2ZjNGI2ZTdkNmI3N2FmNjQ2OTQzMDlmNGQ4YTkxNGNjYTEzY2UyYzBlZDA3NWFlMjA0NjRkMjYzN2QyOWJhMTVhMzIyNmFhYWM1YmE4MTA3Zjc4NGFkOWFkMDM0MjllMjBhOTEzYWRmMDc0YzRmZWFkNjY1MDUwODc5ZTEwYTMwZDc5YzMxY2NlNDRjN2QwYWJiYTYzYzc0NWUzMDNiMDE1ZjlkMjMzZWVlMDU4NTE0NmIwYzdhYTIxY2RkYWZjMGQ5YzJmMGRiNzA5Y2NkNGIxYzk3YzVkN2EwODQ1MjZhYTE4Y2M0ODM1ZThlODY5Mjg5ZTY1YjYxMmJiMzU0YzlmOTE0YjE3Yzc0YWJmNjRkN2VlMDZiOGI0Y2VhY2FmZmZiNTc5ZTUyMTlmMzNiMGI2ZTBkZWQ2YzkyMWViYTE0ZWM1MDY4Zjg0ZGUwMzBiNjY3YTZiMjE0NTM4N2VkZWY4Y2Y1YjU3Nzk2NjY3MTE3Njg3ZDZmZGZhNTM5MGY0NDk5ODQ5ZmU4ZmY1YSJ9.PrHjDtAmGHqbDx73gM-zRoQkb_7b8jZOdvhY6Rz-utc",properties);
    }


}